package itxx.itxx;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        String score = request.getParameter("score");

        //将数据保存到stu.txt文件中
        //将stu.txt文件存储在项目的web目录下
        //1,获取ServletContext对象
        //this.getServletConfig().getServletContext()
        ServletContext servletContext = this.getServletContext();
        //2,调用获取真实路径的方法
        String realPath = servletContext.getRealPath("/stu.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(realPath, true));
        bw.write(username + "," + age + "," + score);
        bw.newLine();
        bw.close();
        //响应客户端浏览器
        PrintWriter pw = response.getWriter();
        pw.println("Save Success");
        pw.close();
        String contextPath = request.getContextPath();
        System.out.println("虚拟目录是" + contextPath);
        String username1 = request.getHeader("username");
        System.out.println("从浏览器输入的用户名" + username1);
      /*  BufferedReader br = request.getReader();
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();*/
    }
}
